#-*- coding: cp950 -*-
#-*- coding: utf-8 -*-
'''
Created on 2013/7/4

@author: jchchen
'''
from django.http import HttpResponse, HttpResponseNotFound
from events.models import Event, Participant
import StringIO

class CSVResponse(HttpResponse):
    def __init__(self, event_id, event_columns, parti_columns, output_name='data', headers=None, encoding='utf8'):
        data = ""
        destEvent = Event.objects.get(pk=event_id)
        if destEvent is None:
            return HttpResponseNotFound('<h1>Error: event id not found"</h1>')
        
        # event key list
        ekl = event_columns
        # event data
        ed = "" 
        for k in ekl:
            data += k
            data += ','
            try:
                attr = getattr(destEvent, k)
                if not isinstance(attr, unicode):
                    ed += unicode("" if attr==None else attr)
                else:
                    ed += attr
                ed += ','
            except AttributeError:
                print 'wrong key of event object', k
                continue
        data += "\n"
        data += ed
        data += "\n"
        
        # participant ket list
        pkl = parti_columns
        for k in pkl:
            data += k
            data += ','
        data += "\n"
        # participants list
        psl = list(Participant.objects.filter(event__pk = event_id ))
        for p in psl:
            for k in pkl:
                try:
                    attr = getattr(p, k)
                    if not isinstance(attr, unicode):
                        data += unicode("" if attr==None else attr)
                    else:
                        data += attr
                    data += ','
                except AttributeError:
                    print 'wrong key of participant object', k
                    continue
            data += "\n"
        
        
        output = StringIO.StringIO()
        # add BOM of utf-8, make sure Chinese can display correctly 
        output.write(u'\ufeff')
        output.write(data)

        mimetype = 'text/csv'
        file_ext = 'csv'
        output.seek(0)
        super(CSVResponse, self).__init__(content=output.getvalue(),
                                            mimetype=mimetype)
        self['Content-Disposition'] = 'attachment;filename="%s.%s"' % \
            (output_name.replace('"', '\"'), file_ext)